package com.heima.datasync.service.impl;

import com.google.common.collect.Lists;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.constants.search.SearchConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    EsService<SearchArticleVO> esService;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult dataInit() {
        //1.判断一下指定的索引库是否存在
        boolean b = esService.existIndex(SearchConstants.ARTICLE_INDEX_NAME);
        //2.如果索引库存在 删除索引库
        if (b) {
            esService.deleteIndex(SearchConstants.ARTICLE_INDEX_NAME);
        }
        //3.创建索引库
        esService.createIndex(SearchConstants.ARTICLE_INDEX_MAPPING, SearchConstants.ARTICLE_INDEX_NAME);

        //4.才能够数据库中查询文章数据
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        if (CollectionUtils.isEmpty(allArticles)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据库中不存在文章数据");
        }

        //5.将文章数据批量导入到ES索引库中
        // 批量插入: 1000 ~ 5000
        List<List<ApArticle>> partition = Lists.partition(allArticles,1000);
        for (List<ApArticle> apArticles : partition) {
            List<SearchArticleVO> articleVOList = apArticles.stream()
                    .map(apArticle -> {
                        SearchArticleVO searchArticleVO = new SearchArticleVO();
                        BeanUtils.copyProperties(apArticle, searchArticleVO);
                        return searchArticleVO;
                    }).collect(Collectors.toList());
            esService.saveBatch(articleVOList, SearchConstants.ARTICLE_INDEX_NAME);
        }

        return ResponseResult.okResult();
    }
}
